using UnityEngine;

public class PlayerCon : MonoBehaviour
{
    private bool _isMoveingforward;
    private bool _isMoveingBack;

    private float _turnDirection;
    private Rigidbody2D _rigidbody;

    [SerializeField]
    private float _playerMoveSpeed;
    [SerializeField]
    private float _turnSpeed;
    [SerializeField]
    private GameObject _bullet;
    [SerializeField]
    private GameManager _gameManager;

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        //检测玩家是否移动
        _isMoveingforward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);
        _isMoveingBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow);

        //检测玩家是否旋转
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            _turnDirection = 1.0f;
        }
        else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            _turnDirection = -1.0f;
        }else
        {
            _turnDirection = 0f;
        }

        // 发射子弹
        // 计算面朝方向的前方偏移
        // 使用 transform.up（玩家的本地 Y 轴方向）动态计算偏移向量：
        Vector2 forwardOffset = transform.up * 0.6f;

        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
        {
            GameObject Bullet = GameObject.Instantiate(_bullet, 
                transform.position + (Vector3)forwardOffset, // 转化为世界坐标系
                this.transform.rotation);
            Bullet.GetComponent<BulletCon>().Fire(this.transform.up);
        }
    }

    private void FixedUpdate()
    {
        if (_isMoveingforward)
        {
            _rigidbody.AddForce(transform.up * _playerMoveSpeed);
        }else if (_isMoveingBack)
        {
            _rigidbody.AddForce(-transform.up * _playerMoveSpeed);
        }

        if (_turnDirection != 0f)
        {
            _rigidbody.AddTorque(_turnDirection * _turnSpeed);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Asteroid"))
        {
            this.gameObject.SetActive(false);
            _gameManager.PlayerDied();
        }
    }
}
